package com.dayaokeji.rhythmschoolstudent.client.main;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.provider.Settings;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.dayaokeji.rhythmschoolstudent.R;
import com.dayaokeji.rhythmschoolstudent.client.common.ActivityStackManager;
import com.dayaokeji.rhythmschoolstudent.client.mine.account.StudentIdLoginActivity;
import com.dayaokeji.rhythmschoolstudent.client.mine.account.bean.RemoteHostPicker;
import com.dayaokeji.rhythmschoolstudent.databases.dao.UserInfoDao;
import com.dayaokeji.rhythmschoolstudent.utils.PrefUtils;
import com.dayaokeji.rhythmschoolstudent.utils.RemoteHostUtil;
import com.dayaokeji.rhythmschoolstudent.utils.ServerCallback;
import com.dayaokeji.rhythmschoolstudent.utils.ToastUtils;
import com.dayaokeji.rhythmschoolstudent.utils.UserUtils;
import com.dayaokeji.server_api.ApiUtils;
import com.dayaokeji.server_api.ServerResponse;
import com.dayaokeji.server_api.api.SystemApi;
import com.dayaokeji.server_api.domain.UserInfo;
import com.facebook.stetho.common.LogUtil;
import com.orhanobut.logger.Logger;
import com.qq.e.ads.splash.SplashAD;
import com.qq.e.ads.splash.SplashADListener;
import com.qq.e.comm.util.AdError;

import java.util.ArrayList;
import java.util.List;

import me.jessyan.retrofiturlmanager.RetrofitUrlManager;
import retrofit2.Call;

public class OpenAdverActivity extends AppCompatActivity implements SplashADListener {
    private SplashAD splashAD;
    private ViewGroup container;
    private TextView skipView;
    private ImageView splashHolder;
    private static final String SKIP_TEXT = "点击跳过 %d";
    public boolean canJump = false;
    /**
     * 为防止无广告时造成视觉上类似于"闪退"的情况，设定无广告时页面跳转根据需要延迟一定时间，demo
     * 给出的延时逻辑是从拉取广告开始算开屏最少持续多久，仅供参考，开发者可自定义延时逻辑，如果开发者采用demo
     * 中给出的延时逻辑，也建议开发者考虑自定义minSplashTimeWhenNoAD的值（单位ms）
     **/
    private int minSplashTimeWhenNoAD = 2000;
    private Handler handler = new Handler(Looper.getMainLooper());
    /**
     * 记录拉取广告的时间
     */
    private long fetchSplashADTime = 0;
    private Handler mainHandler;

    private static final SystemApi systemApi = ApiUtils.getApi(SystemApi.class);
    private Call<ServerResponse<String>> refreshTokenCall;
    private String appId;
    private String adId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_open_adver);

        container = (ViewGroup)this.findViewById(R.id.splash_container);

        skipView = (TextView)findViewById(R.id.skip_view);

        //个地方放你自己的appID
        appId = "1101152570";
        //这个地方放自己的adID
        adId = "8863364436303842593";



        if (Build.VERSION.SDK_INT >= 23) {
            checkAndRequestPermission();
        } else {
            fetchSplashAD(this,container,skipView, appId, adId,this,3000);
        }

    }



    private Runnable startLoginRunnable = () -> setBaseUrl();

    private void setBaseUrl() {
        RemoteHostPicker currentRemoteHost = RemoteHostUtil.getCurrentRemoteHost();
        if (currentRemoteHost != null) {
            String host = currentRemoteHost.getHost();
            if (!TextUtils.isEmpty(host)) {
                RetrofitUrlManager.getInstance().setGlobalDomain(host);
                if (UserUtils.isExpiresLogin()) {
                    refresh();
                }else{
                    startMain();
                }
            }else{
                UserUtils.setAccessToken("");
                UserUtils.setUserInfo(null);
                UserInfoDao.delUserInfo();
                Intent intent = new Intent(OpenAdverActivity.this, StudentIdLoginActivity.class);
                startActivity(intent);
                finish();
            }
        }else{
            UserUtils.setAccessToken("");
            UserUtils.setUserInfo(null);
            UserInfoDao.delUserInfo();
            Intent intent = new Intent(OpenAdverActivity.this, StudentIdLoginActivity.class);
            startActivity(intent);
            finish();
        }
    }

    private void startMain() {
        if (UserUtils.checkLogin(this)) {
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);
            ActivityStackManager.finish();
        }
    }

    private void refresh() {
        final UserInfo userInfo = UserUtils.getUserInfo();
        if (userInfo != null) {
            final String token = userInfo.getToken();
            if (!TextUtils.isEmpty(token)) {
                refreshToken();
            }else {
                UserUtils.setAccessToken("");
                UserUtils.setUserInfo(null);
                UserInfoDao.delUserInfo();
                Intent intent = new Intent(OpenAdverActivity.this, StudentIdLoginActivity.class);
                startActivity(intent);
                finish();
            }
        }else{
            UserUtils.setAccessToken("");
            UserUtils.setUserInfo(null);
            UserInfoDao.delUserInfo();
            Intent intent = new Intent(OpenAdverActivity.this, StudentIdLoginActivity.class);
            startActivity(intent);
            finish();
        }
    }
    /**
     * 刷新Token
     */
    private void refreshToken() {
        refreshTokenCall = systemApi.refreshToken();
        refreshTokenCall.enqueue(new ServerCallback<String>() {
            @Override
            public void onResponse(boolean success, ServerResponse<String> response) {
                if (success) {
                    Logger.d("new token = "+response.getBody());
                    PrefUtils.setExpiresLoginTime(System.currentTimeMillis());
                    UserUtils.setAccessToken(response.getBody());
                    startMain();
                }else{
                    ToastUtils.info("自动登录失败，请重新登录");
                    UserUtils.setUserInfo(null);
                    UserInfoDao.delUserInfo();
                    Intent intent = new Intent(OpenAdverActivity.this, StudentIdLoginActivity.class);
                    startActivity(intent);
                    finish();
                }
            }

            @Override
            public void onFailure(Call<ServerResponse<String>> call, Throwable t) {
                super.onFailure(call, t);
                ToastUtils.info("自动登录失败，请重新登录");
                UserUtils.setUserInfo(null);
                UserInfoDao.delUserInfo();
                Intent intent = new Intent(OpenAdverActivity.this, StudentIdLoginActivity.class);
                startActivity(intent);
                finish();
            }
        });
    }
    @TargetApi(Build.VERSION_CODES.M)
    private void checkAndRequestPermission() {
        List<String> lackedPermission = new ArrayList<String>();
        if (!(checkSelfPermission(Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED)) {
            lackedPermission.add(Manifest.permission.READ_PHONE_STATE);
        }

        if (!(checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)) {
            lackedPermission.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }

        if (!(checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)) {
            lackedPermission.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }

        // 权限都已经有了，那么直接调用SDK
        if (lackedPermission.size() == 0) {
            fetchSplashAD(this,container,skipView,appId,adId,this,3000);
        } else {
            // 请求所缺少的权限，在onRequestPermissionsResult中再看是否获得权限，如果获得权限就可以调用SDK，否则不要调用SDK。
            String[] requestPermissions = new String[lackedPermission.size()];
            lackedPermission.toArray(requestPermissions);
            requestPermissions(requestPermissions, 1024);
        }
    }
    private boolean hasAllPermissionsGranted(int[] grantResults) {
        for (int grantResult : grantResults) {
            if (grantResult == PackageManager.PERMISSION_DENIED) {
                return false;
            }
        }
        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1024 && hasAllPermissionsGranted(grantResults)) {
            fetchSplashAD(this,container,skipView,appId,adId,this,3000);
        } else {
            // 如果用户没有授权，那么应该说明意图，引导用户去设置里面授权。
            Toast.makeText(this, "应用缺少必要的权限！请点击\"权限\"，打开所需要的权限。", Toast.LENGTH_LONG).show();
            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
            intent.setData(Uri.parse("package:" + getPackageName()));
            startActivity(intent);
            finish();
        }
    }

    private void fetchSplashAD(Activity activity, ViewGroup adContainer, View skipContainer, String appId, String posId, SplashADListener adListener, int fetchDelay) {
        //fetchSplashADTime = System.currentTimeMillis();
        splashAD = new SplashAD(activity, adContainer, skipContainer, appId, posId, adListener, fetchDelay);
    }

    @Override
    public void onADDismissed() {
        next();
    }
    /**
     * 设置一个变量来控制当前开屏页面是否可以跳转，当开屏广告为普链类广告时，点击会打开一个广告落地页，此时开发者还不能打开自己的App主页。当从广告落地页返回以后，
     * 才可以跳转到开发者自己的App主页；当开屏广告是App类广告时只会下载App。
     */
    private void next() {
//        if (canJump) {
        setBaseUrl();
        this.finish();
//        } else {
//            canJump = true;
//        }
    }
    @Override
    public void onNoAD(AdError adError) {
/**
 * 为防止无广告时造成视觉上类似于"闪退"的情况，设定无广告时页面跳转根据需要延迟一定时间，demo
 * 给出的延时逻辑是从拉取广告开始算开屏最少持续多久，仅供参考，开发者可自定义延时逻辑，如果开发者采用demo
 * 中给出的延时逻辑，也建议开发者考虑自定义minSplashTimeWhenNoAD的值
 **/
        LogUtil.e("adError" + adError.getErrorMsg()+"      "+adError.getErrorCode());
        long alreadyDelayMills = System.currentTimeMillis() - fetchSplashADTime;//从拉广告开始到onNoAD已经消耗了多少时间
        long shouldDelayMills = alreadyDelayMills > minSplashTimeWhenNoAD ? 0 : minSplashTimeWhenNoAD
                - alreadyDelayMills;//为防止加载广告失败后立刻跳离开屏可能造成的视觉上类似于"闪退"的情况，根据设置的minSplashTimeWhenNoAD
        // 计算出还需要延时多久
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                setBaseUrl();
                OpenAdverActivity.this.finish();
            }
        }, shouldDelayMills);
    }

    @Override
    public void onADPresent() {
        LogUtil.e("onADPresent");
    }

    @Override
    public void onADClicked() {
        LogUtil.e("onADClicked");
    }

    @Override
    public void onADTick(long l) {

        skipView.setText(String.format(SKIP_TEXT, Math.round(l / 1000f)));

    }

    @Override
    public void onADExposure() {
        canJump = false;

    }
    @Override
    protected void onPause() {
        super.onPause();
        canJump = false;
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (canJump) {
            next();
        }
        canJump = true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
    }
    /** 开屏页一定要禁止用户对返回按钮的控制，否则将可能导致用户手动退出了App而广告无法正常曝光和计费 */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK || keyCode == KeyEvent.KEYCODE_HOME) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
